package com.cloudcc.mobile.dao.impl;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.apache.http.Header;
import org.xmlpull.v1.XmlPullParser;

import android.util.Xml;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.UpdateVersionEvent;
import com.cloudcc.cloudframe.model.SendPhotoDynamicModel;
import com.cloudcc.cloudframe.model.UpdateModel;
import com.cloudcc.cloudframe.net.ErrorInfo;
import com.cloudcc.cloudframe.net.async.AsyncClient;
import com.cloudcc.cloudframe.net.async.JsonRequest;
import com.cloudcc.mobile.dao.BaseEngine;
import com.cloudcc.mobile.dao.CommonEngine;
import com.cloudcc.mobile.util.UrlTools;
import com.google.gson.JsonObject;
import com.loopj.android.http.TextHttpResponseHandler;

public class CommonEngineImpl extends BaseEngine implements CommonEngine {

	@Override
	public void checkUpdate() {
		final UpdateVersionEvent updateEvent = new UpdateVersionEvent();
		AsyncClient.getInstance().get(UrlTools.updateUrl, null,
				new TextHttpResponseHandler() {

					@Override
					public void onSuccess(int arg0, Header[] arg1, String resp) {
						UpdateModel info = null;
						try {
							ByteArrayInputStream inputStream = new ByteArrayInputStream(
									resp.getBytes("utf-8"));
							info = getUpdataInfo(inputStream);
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						} catch (Exception e) {
							e.printStackTrace();
						}
						updateEvent.setOk(info != null);
						updateEvent.setData(info);
						EventEngine.post(updateEvent);
					}

					@Override
					public void onFailure(int arg0, Header[] arg1, String arg2,
							Throwable arg3) {
						updateEvent.setOk(false);
						updateEvent.setMessage("检测版本失败...");
						EventEngine.post(updateEvent);
					}
				});
	}

	private UpdateModel getUpdataInfo(InputStream is) throws Exception {
		XmlPullParser parser = Xml.newPullParser();
		parser.setInput(is, "utf-8");// 设置解析的数据源
		int type = parser.getEventType();
		UpdateModel info = new UpdateModel();// 实体
		while (type != XmlPullParser.END_DOCUMENT) {
			switch (type) {
			case XmlPullParser.START_TAG:
				if ("version".equals(parser.getName())) {
					info.version = parser.nextText(); // 获取版本号
				} else if ("url".equals(parser.getName())) {
					info.url = parser.nextText();// 获取要升级的APK文件
				} else if ("name".equals(parser.getName())) {
					info.name = parser.nextText(); // 获取要升级的APK文件
				} else if ("description".equals(parser.getName())) {
					info.description = parser.nextText(); // 获取该文件的信息
				}
				break;
			}
			type = parser.next();
		}
		return info;
	}

	@Override
	public void sendSmS(String phoneNumber, String content, String binding) {

	}

}
